package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.IntegralEnum;
import com.atguigu.srb.core.mapper.*;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.pojo.vo.BorrowerAttachVO;
import com.atguigu.srb.core.pojo.vo.BorrowerAuditVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.vo.BorrowerVO;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.util.DictUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.sql.rowset.BaseRowSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author lsyandwh
 * @since 2022-12-02
 */
@Transactional
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Autowired
    private BorrowerAttachMapper borrowerAttachMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private UserIntegralMapper userIntegralMapper;

    @Override
    public Integer getBorrowerStatus(String userId) {

        //1.根据userId查询借款人信息
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        Borrower borrower = baseMapper.selectOne(wrapper);
        //2.如果查询未空则返回默认值未0
        if(null == borrower){
            return 0;
        }
        return borrower.getStatus();
    }

    @Override
    public void saveBorrower(BorrowerVO borrowerVO,String userId) {

        //1.向borrower表中添加数据
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO,borrower);
        UserInfo userInfo = userInfoMapper.selectById(Long.parseLong(userId));
        borrower.setName(userInfo.getName());
        borrower.setMarry(borrowerVO.getMarry());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setUserId(Long.parseLong(userId));
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);

        //2.向borrower_attach表中添加数据
        List<BorrowerAttach> list = borrowerVO.getBorrowerAttachList();
        if(! CollectionUtils.isEmpty(list)){
            //设置borrowerId
            list.forEach(borrowerAttach -> borrowerAttach.setBorrowerId(borrower.getId()));
            borrowerAttachMapper.insertBatch(list);
        }

        //3.更新user_info表中的状态
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public IPage<Borrower> pageList(Integer size, Integer limit, String keyword) {

        IPage<Borrower> page = new Page<>();
        page.setSize(limit);//显示几条数据
        page.setCurrent(size);//第几页数据
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();

        if(! StringUtils.isEmpty(keyword)){
            wrapper.like("name",keyword)
                    .or()
                    .like("mobile",keyword)
                    .or()
                    .like("id_card",keyword);
        }
        IPage<Borrower> iPage = baseMapper.selectPage(page, wrapper);

        return iPage;
    }

    @Override
    public BorrowerDetailVO getBorrowerById(Long id) {

        //1.根据id查询借款人信息
        Borrower borrower = baseMapper.selectById(id);
        BorrowerDetailVO borrowerVO = new BorrowerDetailVO();
        BeanUtils.copyProperties(borrower,borrowerVO);

        //设置节点信息
        borrowerVO.setStatus(BorrowerStatusEnum.getMsgByStatus(borrower.getStatus()));
        borrowerVO.setIndustry(DictUtils.getDictName(dictMapper,"industry",borrower.getIndustry()));
        borrowerVO.setEducation(DictUtils.getDictName(dictMapper,"education",borrower.getEducation()));
        borrowerVO.setIncome(DictUtils.getDictName(dictMapper,"income",borrower.getIncome()));
        borrowerVO.setReturnSource(DictUtils.getDictName(dictMapper,"returnSource",borrower.getReturnSource()));
        borrowerVO.setContactsRelation(DictUtils.getDictName(dictMapper,"relation",borrower.getContactsRelation()));

        borrowerVO.setSex(borrower.getSex() == 1 ? "男" : "女");
        borrowerVO.setMarry(borrower.getMarry() ? "是" : "否");

        //2.查询借款人附件信息
        QueryWrapper<BorrowerAttach> wrapper = new QueryWrapper<>();
        wrapper.eq("borrower_id",id);

        List<BorrowerAttach> list = borrowerAttachMapper.selectList(wrapper);
        List<BorrowerAttachVO> borrowerAttachVOList = new ArrayList<>();
        //将图片与图片类型设置到borrowerVO中
        list.forEach(b -> {
            BorrowerAttachVO borrowerAttachVO = new BorrowerAttachVO();
            borrowerAttachVO.setImageUrl(b.getImageUrl());
            borrowerAttachVO.setImageType(b.getImageType());
            borrowerAttachVOList.add(borrowerAttachVO);
        });

        borrowerVO.setBorrowerAttachVOList(borrowerAttachVOList);

        return borrowerVO;
    }

    @Override
    public void borrowerAudit(BorrowerAuditVO borrowerAuditVO) {

        //1.修改borrower状态
        Borrower borrower = baseMapper.selectById(borrowerAuditVO.getBorrowerId());
        borrower.setId(borrowerAuditVO.getBorrowerId());
        borrower.setStatus(borrowerAuditVO.getStatus());
        baseMapper.updateById(borrower);

        //2.获取用户积分信息
        UserInfo userInfo = userInfoMapper.selectById(borrower.getUserId());
        Integer integral = userInfo.getIntegral();

        //3.判断当前借款人是否通过审核
        if(borrowerAuditVO.getStatus() == 2){

            //4.添加积分
            //添加借款人基本信息积分
            UserIntegral userIntegral = new UserIntegral();
            userIntegral.setUserId(userInfo.getId());
            userIntegral.setIntegral(borrowerAuditVO.getInfoIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_INFO.getMsg());
            userIntegralMapper.insert(userIntegral);

            integral += borrowerAuditVO.getInfoIntegral();

            //添加借款人身份证信息积分
            if(borrowerAuditVO.getIsIdCardOk()){
                integral += IntegralEnum.BORROWER_IDCARD.getIntegral();

                //清除自增主键id
                userIntegral.setId(null);
                userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
                userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
                userIntegralMapper.insert(userIntegral);
            }

            //添加借款人车辆信息积分
            if(borrowerAuditVO.getIsCarOk()){
                integral += IntegralEnum.BORROWER_CAR.getIntegral();

                userIntegral.setId(null);
                userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
                userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
                userIntegralMapper.insert(userIntegral);
            }

            //添加借款人房产信息积分
            if(borrowerAuditVO.getIsHouseOk()){
                integral += IntegralEnum.BORROWER_HOUSE.getIntegral();

                userIntegral.setId(null);
                userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
                userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
                userIntegralMapper.insert(userIntegral);
            }
        }

        //4.修改user_info借款人认证状态，与借款人积分信息
        userInfo.setBorrowAuthStatus(borrower.getStatus());
        userInfo.setIntegral(integral);
        userInfoMapper.updateById(userInfo);
    }
}
